package main

import (
	"ai-gateway/common"
	"ai-gateway/config"
	_ "ai-gateway/config"
	"ai-gateway/db"
	"ai-gateway/proto"
	"context"
	"fmt"
	"net"

	"google.golang.org/grpc"
)

type MonitorServer struct {
	proto.UnimplementedMonitorServiceServer
}

func (s *MonitorServer) ReportLog(ctx context.Context, log *proto.CallLog) (*proto.EmptyResponse, error) {
	//写入call_logs表
	_, err := db.DB.Exec(`
        INSERT INTO call_logs (business_system, provider, token_used, cost, error)
        VALUES (?, ?, ?, ?, ?)
    `, log.BusinessSystem, log.Provider, log.TokenUsed, log.Cost, log.Error)
	if err != nil {
		common.Logger.Warn().Err(err).Msg("日志写入失败")
		return &proto.EmptyResponse{}, err
	}

	common.Logger.Info().
		Str("business_system", log.BusinessSystem).
		Str("provider", log.Provider).
		Int32("token_used", log.TokenUsed).
		Int64("cost", log.Cost).
		Msg("调用日志记录成功")
	return &proto.EmptyResponse{}, nil
}

func main() {
	common.InitLogger("monitor-service")
	if err := db.InitDB(); err != nil {
		common.Logger.Fatal().Err(err).Msg("数据库初始化失败")
	}

	lis, err := net.Listen("tcp", fmt.Sprintf("%s%d", ":", config.Config.MonitorServicePort))
	if err != nil {
		common.Logger.Fatal().Err(err).Msg("监听端口失败")
	}

	s := grpc.NewServer()
	proto.RegisterMonitorServiceServer(s, &MonitorServer{})
	common.Logger.Info().Msg("Monitor Service 启动: :8085")

	if err := s.Serve(lis); err != nil {
		common.Logger.Fatal().Err(err).Msg("服务启动失败")
	}
}
